package treemodel.table;

import document.Context;
import treemodel.Container;
import treemodel.Line;
import treemodel.Node;
import exception.InvalidHtmlDocumentException;
import treeview.NodeView;
import treeview.table.EmptyCellView;
import treeview.table.TableView;

/**
 * Created by Pavel Nikolaev
 */
public class Table extends Container {

    @Override
    public Line createLine() throws InvalidHtmlDocumentException {
        throw new InvalidHtmlDocumentException("Html table doesn't support text placed outside any table cell");
    }

    @Override
    public NodeView createView(Context context) {
        int rowNumber = myNodes.size();
        int columnNumber = 0;
        for (Node row : myNodes) {
            int cellInRow = row.countChildren();
            if (cellInRow > columnNumber) columnNumber = cellInRow;
        }
        TableView tableView = new TableView(rowNumber, columnNumber);
        int i = 0;
        for (Node row : myNodes) {
            int j = 0;
            while (j < row.countChildren()) {
                NodeView cellView = row.getChild(j).createView(context);
                tableView.setCellView(cellView, i, j);
                ++j;
            }
            while (j < columnNumber) {
                NodeView cellView = new EmptyCellView();
                tableView.setCellView(cellView, i, j);
                ++j;
            }
            ++i;
        }
        return tableView;
    }
}
